<template>
  <div class="container">
    <div>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form ref="formSearch" :model="formSearch">
            <el-form-item label="菜品名称：">
              <el-input
                style="width: 150px"
                v-model="formSearch.name"
                placeholder="请输入"
                class="handle-input mr10"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-form ref="formSearch" :model="formSearch">
            <el-form-item label="时  间  段：">
              <el-select
                style="width: 150px"
                v-model="formSearch.type"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in dishTypeList"
                  :key="item.label"
                  :label="item.label"
                  :value="item.label"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-form style="float: left">
            <el-button size="mini" type="primary" @click="personQuery"
              >查 询</el-button
            >
            <el-button size="mini" type="success" @click="showAddDialog"
              >新 增</el-button
            >
          </el-form>
        </el-col>
      </el-row>
      <!-- <el-row :gutter="20">
        <el-col :span="6">
          <el-form style="float: left">
            <el-button size="mini" type="primary" @click="getData"
              >查 询</el-button
            >
            <el-button size="mini" type="success" @click="showAddDialog"
              >新 增</el-button
            >
          </el-form>
        </el-col>
      </el-row> -->
    </div>
    <el-table
      :data="
        tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
      "
      highlight-current-row
    >
      <!-- 菜品名称	时间段	所属食堂	图片路径	ID -->
      <el-table-column
        prop="菜品名称"
        label="菜品名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="时间段"
        label="时间段"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="所属食堂"
        label="所属食堂"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="showUpdateDialog(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            style="color: #ff0000; margin-left: 35px"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.length"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>

    <!-- 弹出框 -->
    <el-dialog
      :title="formDialog.title"
      :visible.sync="formDialog.show"
      @close="handleClosePic"
      width="40%"
    >
      <el-form
        ref="formDialog"
        :model="formDialog"
        label-width="100px"
        class="flex"
      >
        <!-- 姓名,联系电话,密码,机构编号,机构名称,楼宇名称,类型 -->
        <el-form-item label="菜品名称：">
          <el-input
            style="width: 200px"
            v-model="formDialog.DishName"
            placeholder="请输入"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>

        <el-form-item label="时间段：">
          <el-select
            v-model="formDialog.DishType"
            placeholder="请选择"
            style="width: 200px"
          >
            <el-option
              v-for="item in dishTypeAdd"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="openFolder">选择图片</el-button>
          <input
            type="file"
            ref="PicFile"
            style="display: none"
            accept="image/*"
            @change="uploadPic"
          />
        </el-form-item>
        <div style="padding-left: 100px">
          <el-upload
            :file-list="imageUploadList"
            ref="PicUpload"
            list-type="picture"
            :limit="1"
            :on-remove="
              (file, imageUploadList) => {
                handleRemovePic(file, imageUploadList, index)
              }
            "
          >
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过1张。请点击【上传】按钮完成上传操作。
            </div>
          </el-upload>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="formDialog.show = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="照片信息" :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import '@/assets/css/common.css'
import { formatDate } from '@/common/js/date.js'
import OSS from 'ali-oss';
// import export2Excel from '@/utils/exportExcel/index.js'
export default {
  data () {
    return {
      currentPage: 1, //初始页
      pageSize: 10,    //    每页的数据
      formDialog: {},
      OrganizationList: [],
      tableData: [],
      originalData: [],
      formSearch: {
        name: '',
        type: '全部',
      },
      dishTypeList: [{ "label": "全部", "value": "全部" }, { "label": "早餐", "value": "0" }, { "label": "午餐", "value": "1" }, { "label": "晚餐", "value": "2" }],
      dishTypeAdd: [{ "label": "早餐", "value": "0" }, { "label": "午餐", "value": "1" }, { "label": "晚餐", "value": "2" }],

      imageUploadList: [],

      //图片上传
      dataObj: {
        region: 'oss-cn-beijing',//我的存储是北京，可根据具体配置自行修改
        accessKeyId: 'LTAISI12uxTRFccz',
        accessKeySecret: 'cQAvLIZ9JizT5RXRNPBVcXfg3iURD8',
        bucket: 'photo-srw-hb2',
      }, //存签名信息
      baseAli: 'oss-cn-beijing.aliyuncs.com',
    }
  },
  mounted () {
    this.getData()
  },
  methods: {
    // 获取 菜品列表
    async getData () {
      var url = 'System/GetDishInfo?Name=&Type=-1&UserID=' + localStorage.getItem('UserID')
      const { data } = await this.$Http.get(url)
      this.originalData = data
      this.personQuery()
    },
    // 模糊查询
    personQuery () {
      this.currentPage = 1;
      this.tableData = this.originalData

      if (this.formSearch.name) this.tableData = this.tableData.filter(item => item.菜品名称.includes(this.formSearch.name))
      if (this.formSearch.type != '全部') this.tableData = this.tableData.filter(item => item.时间段 === this.formSearch.type)
    },
    // 组织机构 新增
    handleSubmit () {
      if (this.formDialog.title.includes('新增')) {
        this.addData();
      } else {
        this.updateData();
      }
    },
    updateData () {
      if (this.imageUploadList.length) {
        this.formDialog.DishPic = this.imageUploadList[0].url
      } else {
        this.formDialog.DishPic = ''
      }
      console.log(this.formDialog)
      this.$axios({
        url: 'System/UpdateDishInfo',
        method: 'post',
        data: this.formDialog
      }).then(res => {
        console.log(res)
        if (res.data.IsSucess) {
          this.$message.success('编辑成功')
          this.formDialog.show = false;
          this.getData()
        } else {
          this.$message.error('编辑失败' + '，' + res.data.Message);
        }
      })
    },
    addData () {
      if (this.imageUploadList.length) {
        this.formDialog.DishPic = this.imageUploadList[0].url
      } else {
        this.formDialog.DishPic = ''
      }
      console.log(this.formDialog)
      this.$axios({
        url: 'System/AddDishInfo',
        method: 'post',
        data: this.formDialog
      }).then(res => {
        console.log(res)
        if (res.data.IsSucess) {
          this.$message.success('新增成功')
          this.formDialog.show = false;
          this.getData()
        } else {
          this.$message.error('新增失败' + '，' + res.data.Message);
        }
      })
    },
    // 打开新增窗口
    showAddDialog () {
      //清空编辑框
      this.formDialog = {
        title: '新增菜品',
        show: true,
        // info.DishName, info.DishType, info.DishPic, info.OrgID, info.OrgPosition);
        // SELECT 菜品名称,时间段,'',图片路径,楼宇编号,楼宇名称,0
        // 其中，楼宇编号与楼宇名称为人员登录时获取的信息
        DishName: '',
        DishType: '',
        DishPic: '',
        OrgID: localStorage.getItem('OrgID'),
        OrgPosition: localStorage.getItem('DepartmentName'),
      }
    },
    // 打开新增窗口
    showUpdateDialog (index, row) {
      var userData = Object.assign({}, row);
      this.formDialog = {
        title: '编辑菜品',
        show: true,
        DishName: userData.菜品名称,
        DishType: '',
        DishPic: userData.图片路径,
        ID: userData.ID,
      }
      switch (userData.时间段) {
        case '早餐':
          this.formDialog.DishType = '0'
          break;

        case '午餐':
          this.formDialog.DishType = '1'
          break;
        case '晚餐':
          this.formDialog.DishType = '2'
          break;
      }
      this.imageUploadList = []
      if (userData.图片路径 != '') {
        this.imageUploadList.push({ name: '', url: userData.图片路径 })
      }
      console.log(this.formDialog)
    },
    // 删除
    async handleDelete (index, row) {
      var url = 'System/DeleteDishInfo?DishID=' + row.ID
      const { data } = await this.$Http.get(url)
      if (data.IsSucess) {
        this.$message.success('删除成功')
        this.getData()
      } else {
        this.$message.error('删除失败');
      }
    },

    // 放大图片
    handlePreviewPic (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    // 删除图片
    handleRemovePic (file, imageUploadList, index) {
      this.imageUploadList.splice(index, 1);
      console.log(this.imageUploadList)
    },

    // 阿里上传图片
    openFolder () {
      this.$refs.PicFile.click();
    },
    uploadPic () {
      this.readPic(this.$refs.PicFile.files[0]);
      this.$refs.PicFile.value = null; // 移除文件，可以保证上传同样的文件时，也会触发change事件
    },
    // 读取图片
    readPic (file) {
      return new Promise((resolve, reject) => {
        // 此时可以自行将文件上传至服务器
        const that = this
        let client = new OSS(this.dataObj)
        const fileName = file.name
        //定义唯一的文件名，打印出来的uid其实就是时间戳
        //client 是第一步中的 client
        client
          .multipartUpload(fileName, file)
          .then((result) => {
            //下面是如果对返回结果再进行处理，根据项目需要
            // console.log(result)
            var url =
              'https://' +
              result.bucket +
              '.' +
              that.baseAli +
              '/' +
              result.name
            console.log(url)
            that.completeUploadPic(result.name, url)
            resolve()
          })
          .catch((err) => {
            console.log('err:', err)
            reject()
          })
      })
    },
    completeUploadPic (name, url) {
      this.imageUploadList.push({ name: name, url: url })
    },

    // 另存为图片
    convertImageToCanvas (image) {
      var canvas = document.createElement("canvas");
      canvas.width = image.width;
      canvas.height = image.height;
      canvas.getContext("2d").drawImage(image, 0, 0);
      return canvas;
    },
    callback (base64data) {
      console.log(base64data, 'base64data')
      var image = new Image();
      image.src = 'https://t8.baidu.com/it/u=3264179045,3543353687&fm=218&app=126&size=f242,150&n=0&f=JPEG&fmt=auto?s=5BA233637CE8D009067141CA030070B6&sec=1710608400&t=d196c1b2f7097057ad6f42f6ccf7e708';
      image.onload = () => {
        var canvas = this.convertImageToCanvas(image);
        var url = canvas.toDataURL("image/jpeg");
        var bytes = window.atob(url.split(",")[1]);  //通过atob将base64进行编码
        //处理异常，将ASCII码小于0的转换为大于0,进行二进制转换
        var buffer = new ArrayBuffer(bytes.length);
        var uint = new Uint8Array(buffer);  //生成一个8位数的数组
        for (var i = 0; i < bytes.length; i++) {
          uint[i] = bytes.charCodeAt(i);  //根据长度返回相对应的Unicode 编码
        }
        //Blob对象
        var imageFile = new Blob([buffer], { type: "image/jpeg" }); //type为图片的格式  
        //将截图生成的图片传到后台，生成一个完成的连接地址
        let formData = new FormData(); //创建form对象
        formData.append('file', imageFile);
        formData.append('fileName', 'file');
        let config = {
          headers: { 'Content-Type': 'multipart/form-data' }
        };  //添加请求头
        const postUrl = getUploadFileUrl();
        axios.post(postUrl, formData, config)
          .then(response => {
            this.url = getImgUrl() + urlData(response.data.data)
            var a;
            //windows电脑会弹出一个小的浏览框，图片在里面，可右键另存为
            a = window.open(this.url, "_blank", "width=0, height=0");
            a.document.execCommand("SaveAs");
          })
          .catch((err) => {
          });
      };
    },
    // 关闭图片编辑窗口
    handleClosePic () {
      this.imageUploadList = []
      this.$refs.PicUpload.clearFiles()
    },
    // 分页导航
    handlePageChange (currentPage) {
      this.currentPage = currentPage;
      // console.log(this.currentPage)
    },
    handleSizeChange (size) {
      this.pageSize = size;
      // console.log(this.pageSize)
    }
  }
}
</script>
<style>
</style>